<?php

namespace App\Http\Controllers\Api;

use App\AboutUs;
use App\AgentApply;
use App\AgentList;
use App\AgentOrder;
use App\AgentSettleAccountsRecord;
use App\AgentTeam;
use App\Coupons;
use App\Course;
use App\CustomerClue;
use App\Http\Services\CommonManager;
use App\Http\Services\DomainManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\IntegralDetail;
use App\OrderItem;
use App\Orders;
use App\Staff;
use App\User;
use App\UserAddress;
use App\UserAppointment;
use App\UserCoupon;
use App\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use Maatwebsite\Excel\Facades\Excel;
use Predis\Profile\RedisVersion240;

class UCenterController extends Controller
{
    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request)
    {
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'success', 'message' => '请先登录！', 'data' => []]);

        $userBasicInfo = CommonManager::getUserBasicInfo($user->id);

        $user->is_salesman = 0;
        $staffId = Staff::getUserStaffId($user->id);
        if ($staffId) {
            $user->is_salesman = $staffId;
        }

        $user->user_info = $userBasicInfo;

        if (empty($user->phone) || empty($userBasicInfo['realname']) || empty($userBasicInfo['company_name'])){
            $user->is_perfect_info = 0;
        }else{
            $user->is_perfect_info = 1;
        }

        $user->is_agent = AgentList::inspectUserWhetherAgent($user->id);

        $user->agent_balance = 0;
        if($user->is_agent == 1){
            $agent = AgentList::whereUserId($user->id)->first();
            $user->agent_balance = $agent ? $agent->balance : 0;
        }

        $user->is_agent_apply = 0;
        $agentApply = AgentApply::whereUserId($user->id)->orderByDesc('created_at')->first();
        if($agentApply){
            if($agentApply->review == 0){
                $user->is_agent_apply = 1;
            }elseif($agentApply->review == 1){
                $user->is_agent_apply = 2;
            }
        }

        $user->customer_service_phone = '18502079989';

        return response()->json(['level' => 'success','message' => '获取成功','data' => $user]);
    }

    /**
     * 设置用户资料
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUserInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'success','message' => '请先登录！','data' => []]);

        $nickname = $request->get("nickname");
        $realname = $request->get("realname");
        $photoId  = $request->get("photo_id");
        $sex      = $request->get("sex");
        $province = $request->get("province");
        $city     = $request->get("city");
        $area     = $request->get("area");
        $birthday = $request->get("birthday");
        $companyName = $request->input('company_name') ?? '';
        $phone = $request->get('phone') ?? '';

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '手机号不能为空']);

        $phoneVerification = CommonManager::phoneVerification($phone);
        if(!$phoneVerification)
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        $isPhone = User::wherePhone($phone)->whereRole(0)->first();
        $userInfo = UserInfo::whereUserId($user->id)->first();
        if(!$userInfo){
            if($isPhone)
                return response()->json(['level' => 'error','message' => '该手机号已被注册']);

            $userInfo = new UserInfo();
            $userInfo->user_id = $user->id;
        }else{
            if($isPhone && ($isPhone->id != $userInfo->user_id))
                return response()->json(['level' => 'error','message' => '该手机号已被注册']);
        }

        if(!is_null($nickname))$userInfo->nickname = $nickname;
        if(!is_null($realname))$userInfo->realname = $realname;
        if(!is_null($sex))$userInfo->sex = $sex;
        if(!is_null($photoId))$userInfo->photo_id = $photoId;
        if(!is_null($province))$userInfo->province = $province;
        if(!is_null($city))$userInfo->city = $city;
        if(!is_null($area))$userInfo->area = $area;
        if(!is_null($birthday))$userInfo->birthday = $birthday;
        $userInfo->company_name = $companyName;
        $userInfo->save();

        $user->phone = $phone;
        $user->save();

        $thisCustomer = CustomerClue::whereUserId($user->id)->first();
        if($thisCustomer){
            $thisCustomer->contact = $phone;
            $thisCustomer->save();
        }else{
            $thisCustomerPHone = CustomerClue::whereContact($phone)->first();
            if($thisCustomerPHone){
                $thisCustomerPHone->user_id = $user->id;
                $thisCustomerPHone->save();
            }else{
                $thisCustomer = new CustomerClue();
                $thisCustomer->user_id = $user->id;
                $thisCustomer->customer_name = $userInfo->realname ? $userInfo->realname : $userInfo->nickname;
                $thisCustomer->contact = $phone;
                $thisCustomer->save();
            }
        }

        $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);

        return response()->json(['level' => 'success','message' => '设置成功','data' => $userInfo]);
    }

    public function joinAgentTeam(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'success','message' => '请先登录!','data' => []]);

        $inviteUserId   = $request->input('invite_user_id') ?? 0;

        $result = AgentTeam::join($user->id,$inviteUserId);

        if($result){
            return response()->json(['level' => 'success','message' => '加入成功']);
        }else{
            return response()->json(['level' => 'success','message' => '加入失败']);
        }
    }

    /**
     * 获取我的优惠券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserCoupon(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'success','message' => '请先登录!','data' => []]);

        $type  = $request->input('type')  ?? '';
        $limit = $request->input('limit',10);
        $page  = $request->input('page',1);

        $pageInfo = [
            'limit' => $limit,
            'page'  => $page,
            'type'  => $type
        ];
        $page=$page-1;
        $userCoupon = UserCoupon::whereUserId($user->id);
        if($type == 'unused'){
            $userCoupon=$userCoupon->whereIsUse(0)
                ->whereIsLocking(0)
                ->where('end_time','>', date('Y-m-d H:i:s',time()));
        }else if($type == 'used'){
            $userCoupon = $userCoupon->whereIsUse(1);
        }else if($type == 'expired'){
            $userCoupon = $userCoupon->where('end_time','<=', date('Y-m-d H:i:s',time()));
        }

        $pageInfo['total'] = $userCoupon->count();

        $userCoupon = $userCoupon->orderBy('created_at','desc')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userCoupon,'page_info' => $pageInfo]);
    }

    /**
     * 获取关于我们
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAboutUs(Request $request){
        $aboutUs = AboutUs::whereType('about_us')
            ->first();
        if($aboutUs){
            if($aboutUs->content){
                $newImgUrl = env("OSS_FILE_URL") . env("OSS_FILE_DIR");
                $aboutUs->content = str_replace("https://wxapp.nsitp.cn/",$newImgUrl,$aboutUs->content);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $aboutUs,'customer_service_phone' => '18502079989']);
    }

    /**
     * 获取联系客服
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getContactCustomerService(Request $request){
        $customerService = AboutUs::whereType('customer_service')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $customerService]);
    }

    /**
     * 获取个人合作协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPersonalCooperationAgreement(Request $request){
        $personalCooperationAgreement = AboutUs::whereType('personal_cooperation_agreement')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $personalCooperationAgreement]);
    }

    /**
     * 获取企业合作协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseCooperationAgreement(Request $request){
        $enterpriseCooperationAgreement = AboutUs::whereType('enterprise_cooperation_agreement')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseCooperationAgreement]);
    }

    public function getMyIntegralInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);
        $limit = $request->input('limit',10) ;
        $page  = $request->input('page',1);
        $type  = $request->input('type','add');
        $way   = $request->input('way');
        $page_info = [
            'limit' => $limit,
            'page'  => $page,
            'type'  =>'',
            'total' => 0,
            'way_total' => 0
        ];
        $page=$page-1;
        if (!in_array($type,['use','add']))
            return response()->json(['level' => 'error','message' => '参数错误！','data' => []]);
        $data  = IntegralDetail::whereUserId($user->id);
        $data  = $data->whereType($type);
        $page_info['total'] = $data->count();

        if ($way == 'question') {
            $data = $data->where('question_id','<>',0);
            $data = $data->whereCourseId(0);
            $data = $data->whereOrderNum('');
        } elseif ($way == 'course') {
            $data = $data->where('course_id','<>',0);
            $data = $data->whereQuestionId(0);
            $data = $data->whereOrderNum('');
        } elseif ($way == 'order') {
            $data = $data->where('order_num','<>','');
            $data = $data->whereQuestionId(0);
            $data = $data->whereCourseId(0);
        }
        $page_info['way_total'] = $data->count();
        $data  = $data->offset($page * $limit)
            ->limit($limit)
            ->get();
        $used = IntegralDetail::whereUserId($user->id)->whereType('use')->sum('integral_num');
        $result=[
            'remain_integral'   => UserInfo::getUserIntegral($user->id),
            'used_integral'     => $used ? $used : 0,
            'record'=>$data
        ];
        return response()->json(['level' => 'success','message' => '获取成功','data' => $result ,'page_info'=>$page_info]);
    }

    public function getPersonCardInfo(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $userStaff = Staff::whereUserId($user->id)->first();

        if(!$userStaff){
            return response()->json(['level' => 'success','message' => '获取成功','data' => null]);
        }

        if($userStaff->qrcode_img_id == 0){
            $scene = "user_id=$user->id";
            $path  = 'pages/businessCard/initalState?' . $scene;

            //生成微信小程序的二维码图片
            $wxAppQrCodeContent = WechatLogin::getWxaCodeBYToken($path);
            if($wxAppQrCodeContent) {
                //获取二维码图片
                $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(200, 200)->encode("image/jpeg");
                $qrcodeFile = FileManager::saveFileByFileContent($wxAppQrCodeImgINfo->encoded, 'card_qrcode_img.jpg', $wxAppQrCodeImgINfo->mime());
                $imageModel = new Images();
                $imageModel->files()->associate($qrcodeFile);
                $imageModel->img_type = $qrcodeFile->file_type;
                $imageModel->img_name = $qrcodeFile->file_name;
                $imageModel->save();

                $userStaff->qrcode_img_id = $imageModel->id;
                $userStaff->save();
            }
        }

        $userStaff->person_img_url = FileManager::getImgUrl($userStaff->person_img_id);
        if($userStaff->share_img_id != 0){
            $userStaff->share_img_url = FileManager::getImgUrl($userStaff->share_img_id);
        }else{
            $userStaff->share_img_url = null;
        }

        if($userStaff->qrcode_img_id != 0){
            $userStaff->qrcode_img_url = FileManager::getImgUrl($userStaff->qrcode_img_id);
        }else{
            $userStaff->qrcode_img_url = null;
        }
        return response()->json(['level' => 'success','message' => '获取成功','data' => $userStaff]);
    }

    public function getPersonCardInfoByUserId(Request $request){
        $userId = $request->get("user_id");

        $userStaff = Staff::whereUserId($userId)->first();

        if(!$userStaff){
            return response()->json(['level' => 'error','message' => '名片信息不存在或已删除','data' => null]);
        }

        $userStaff->person_img_url = FileManager::getImgUrl($userStaff->person_img_id);
        return response()->json(['level' => 'success','message' => '获取成功','data' => $userStaff]);
    }

    public function setPersonCardInfo(Request $request){
        $personImgId     = $request->get("person_img_id");
        $realname        = $request->get("realname");
        $phone           = $request->get("phone");
        $introduce       = $request->get("introduce");
        $addressProvince = $request->get("address_province");
        $addressCity     = $request->get("address_city");
        $addressArea     = $request->get("address_area");
        $addressDetail   = $request->get("address_detail");
        $email           = $request->get("email");
        $position        = $request->get("position");

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $userStaff = Staff::whereUserId($user->id)->first();

        if(!$userStaff){
            $userStaff = new Staff();
            $userStaff->user_id = $user->id;
        }

        if(!is_null($personImgId) && $personImgId != 0)$userStaff->person_img_id = $personImgId;
        if(!is_null($realname))$userStaff->realname = $realname;
        if(!is_null($phone))$userStaff->phone = $phone;
        if(!is_null($introduce))$userStaff->introduce = $introduce;
        if(!is_null($addressProvince))$userStaff->address_province = $addressProvince;
        if(!is_null($addressCity))$userStaff->address_city = $addressCity;
        if(!is_null($addressArea))$userStaff->address_area = $addressArea;
        if(!is_null($addressDetail))$userStaff->address_detail = $addressDetail;
        if(!is_null($email))$userStaff->email = $email;
        if(!is_null($position))$userStaff->position = $position;

        $userStaff->save();

        self::buildPersonCardShareImg($userStaff);

        return response()->json(['level' => 'success','message' => '设置成功','data' => $userStaff]);

    }

    public static function buildPersonCardShareImg(Staff $staff){
//        $staff = Staff::whereUserId(2)->first();
        //背景图片
        $backgroundImgInfo = Image::make(url('images/card_share_bg.png'));

//        $realname = $staff->realname;
//        //真实姓名
//        $backgroundImgInfo->text($realname, 45, 95, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(30);
//            $font->color('#ffffff');//5a5a5a
//            $font->align('left');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        $position = mb_substr($staff->position,0,8,'utf-8');
//        //职位
//        $backgroundImgInfo->text($position, 43, 165, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(20);
//            $font->color('#ffffff');//5a5a5a
//            $font->align('left');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        $phone = $staff->phone;
//        //手机号
//        $backgroundImgInfo->text($phone, 485, 188, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(18);
//            $font->color('#2f2e2e');//5a5a5a
//            $font->align('right');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        $email = $staff->email;
//        //手机号
//        $backgroundImgInfo->text($email, 485, 237, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(18);
//            $font->color('#2f2e2e');//5a5a5a
//            $font->align('right');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        $address = $staff->address_province.$staff->address_city.$staff->address_area.$staff->address_detail;
//        //手机号
//        $backgroundImgInfo->text($address, 485, 283, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(18);
//            $font->color('#2f2e2e');//5a5a5a
//            $font->align('right');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        $personImgInfo = Image::make(FileManager::getImgUrl($staff->person_img_id))->resize(100, 100);
//        $personImgInfo->ellipse(5, 5, 0, 0, function ($draw) {//定义椭圆跟圆一致
//            $draw->background('#ffffff');
//            $draw->border(1, '#ff0000');
//        });
//        $backgroundImgInfo->insert($personImgInfo,'top-left',434,60);

        $personImgInfo = Image::make(FileManager::getImgUrl($staff->person_img_id))->resize(910, 600);
//        $personImgInfo = Image::make(url('images/kecheng.png'))->resize(910, 600);
        $backgroundImgInfo->insert($personImgInfo,'top-left',45,60);

        if($staff->qrcode_img_id == 0){
            $scene = "user_id=$staff->user_id";
            $path  = 'pages/businessCard/initalState?' . $scene;

            //生成微信小程序的二维码图片
            $wxAppQrCodeContent = WechatLogin::getWxaCodeBYToken($path);
            if($wxAppQrCodeContent) {
                //获取二维码图片
                $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(200, 200)->encode("image/jpeg");
                $qrcodeFile = FileManager::saveFileByFileContent($wxAppQrCodeImgINfo->encoded, 'card_qrcode_img.jpg', $wxAppQrCodeImgINfo->mime());
                $imageModel = new Images();
                $imageModel->files()->associate($qrcodeFile);
                $imageModel->img_type = $qrcodeFile->file_type;
                $imageModel->img_name = $qrcodeFile->file_name;
                $imageModel->save();

                $staff->qrcode_img_id = $imageModel->id;
                $staff->save();
            }
        }

        $qrcodeImgInfo = Image::make(FileManager::getImgUrl($staff->qrcode_img_id))->resize(280, 280);
//        $qrcodeImgInfo = Image::make(url('images/renxieqrcode.jpg'))->resize(280, 280);
        $backgroundImgInfo->insert($qrcodeImgInfo,'top-left',43,1220);
        $backgroundImgInfo->encode('jpg');
        //输出图片
        $qrcodeFile = FileManager::saveFileByFileContent($backgroundImgInfo->encoded, 'card_share_img.jpg');
        $imageModel = new Images();
        $imageModel->files()->associate($qrcodeFile);
        $imageModel->img_type = $qrcodeFile->file_type;
        $imageModel->img_name = $qrcodeFile->file_name;
        $imageModel->save();

        $staff->share_img_id = $imageModel->id;
        $staff->save();

        return $staff;

//        $response = response()->make($backgroundImgInfo->encode('jpg'));
//        $response->header('Content-Type', 'image/jpeg');
//        return $response;
    }

    /**
     * 获取代理人的团队
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAgentTeamList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $data = AgentTeam::getSonUser($user->id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }

    /**
     * 获取推广订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAgentOrderList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page'  => $page
        ];

        $isAgent = AgentList::inspectUserWhetherAgent($user->id);
        if(!$isAgent)
            return response()->json(['level' => 'success','message' => '获取成功','data' => []]);

        /** @var AgentOrder $agentOrderList */
        $agentOrderList = AgentOrder::where('id','>',0);

        if($isAgent == 1){
            $agentOrderList = $agentOrderList->whereAgentUserId($user->id);
        }elseif($isAgent == 2){
            $agentOrderList = $agentOrderList->whereSonAgentUserId($user->id);
        }

        $pageInfo['total'] = $agentOrderList->count();

        $agentOrderList = $agentOrderList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($agentOrderList) > 0){
            foreach ($agentOrderList as $agentOrder) {
                if($isAgent == 2){
                    $agentOrder->agent_fee = '';
                }

                $agentOrder->course_name = '';
                $order = Orders::whereOrderNum($agentOrder->order_num)->first();
                if($order){
                    $orderItem = OrderItem::whereOrderId($order->id)->first();
                    if($orderItem){
                        $course = Course::whereId($orderItem->course_id)->first();
                        $agentOrder->course_name = $course ? $course->name : '';
                    }
                }

                $orderUserInfo = CommonManager::getUserBasicInfo($agentOrder->buyer_user_id);
                $agentOrder->order_user_name = $orderUserInfo ? $orderUserInfo['nickname'] : '';
                $agentOrder->order_user_photo_url = $orderUserInfo ? $orderUserInfo['photo_url'] : '';

                $agentOrder->invite_user_name = '';
                $agentOrder->invite_user_photo_url = '';
                if($agentOrder->buyer_user_id == $agentOrder->son_agent_user_id){
                    $inviteUserInfo = CommonManager::getUserBasicInfo($agentOrder->agent_user_id);
                    $agentOrder->invite_user_name = $inviteUserInfo ? $inviteUserInfo['nickname'] : '';
                    $agentOrder->invite_user_photo_url = $inviteUserInfo ? $inviteUserInfo['photo_url'] : '';
                }else{
                    $inviteUserInfo = CommonManager::getUserBasicInfo($agentOrder->son_agent_user_id);
                    $agentOrder->invite_user_name = $inviteUserInfo ? $inviteUserInfo['nickname'] : '';
                    $agentOrder->invite_user_photo_url = $inviteUserInfo ? $inviteUserInfo['photo_url'] : '';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $agentOrderList,'page_info' => $pageInfo]);
    }

    /**
     * 结算记录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSettleAccountsRecordList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $limit = $request->input('limit') ?? 20;
        $page = $request->input('page') ?? 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        $isAgent = AgentList::inspectUserWhetherAgent($user->id);
        if($isAgent != 1)
            return response()->json(['level' => 'success','message' => '获取成功','data' => []]);

        /** @var AgentSettleAccountsRecord $agentSettleAccountRecord */
        $agentSettleAccountRecordList = AgentSettleAccountsRecord::whereAgentUserId($user->id);

        $pageInfo['total'] = $agentSettleAccountRecordList->count();

        $agentSettleAccountRecordList = $agentSettleAccountRecordList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($agentSettleAccountRecordList) > 0){
            foreach ($agentSettleAccountRecordList as $agentSettleAccountRecord) {
                $agent = AgentList::whereUserId($agentSettleAccountRecord->agent_user_id)->first();
                if($agent){
                    if($agent->type == 'personal'){
                        $agent->type_name = '个人';
                    }elseif($agent->type == 'enterprise'){
                        $agent->type_name = '企业';
                    }else{
                        $agent->type_name = $agent->type;
                    }
                }

                $agentSettleAccountRecord->agent_info = $agent;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $agentSettleAccountRecordList,'page_info' => $pageInfo]);
    }

    /**
     * 线下预约一对一
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUserAppointment(Request $request) {
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => []]);

        $realname = $request->get('realname', '');
        $phone = $request->get('phone', '');
        $booking_time = $request->get('booking_time', '');

        if($realname == '' && !is_null($realname))
            return response()->json(['level' => 'error','message' => '姓名不能为空！','data' => []]);

        if($phone == '' && !is_null($phone))
            return response()->json(['level' => 'error','message' => '手机号不能为空']);

        $phoneVerification = CommonManager::phoneVerification(trim($phone));
        if(!$phoneVerification)
            return response()->json(['level' => 'error','message' => '手机号格式不正确']);

        if($booking_time == '' && !is_null($booking_time))
            return response()->json(['level' => 'error','message' => '预约日期不能为空']);

        $appointment = new UserAppointment();

        $appointment->user_id = $user->id;
        if(!is_null($realname))$appointment->realname = $realname;
        if(!is_null($phone))$appointment->phone = $phone;
        if(!is_null($booking_time))$appointment->booking_time = $booking_time;
        $appointment->status = 0;

        $appointment->save();

        return response()->json(['level' => 'success','message' => '预约成功','data' => $appointment]);
    }
}
